﻿using Application.Commons.Data;
using AutoMapper;
using Domain.Entities.Customers;
using FrameworkCore.Attributes;
using FrameworkCore.Helpers;
using FrameworkCore.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using NM.Module.Auth.API.Configurations;
using NM.Module.Auth.API.Interfaces;
using System.ComponentModel.DataAnnotations;

namespace NM.Module.Auth.API.Commands.Register;

#nullable disable

/// <summary>
/// 刷新令牌
/// </summary>
[Map(typeof(Customer))]
public class RegisterCommand : IRequest<Result<bool>>
{
    /// <summary>
    /// 用户名
    /// </summary>
    [Required(ErrorMessage = "用户名是必填的")]
    public string Username { get; set; }

    /// <summary>
    /// 邮箱
    /// </summary>
    [EmailAddress]
    [Required(ErrorMessage = "邮箱是必填的")]
    public string Email { get; set; }

    /// <summary>
    /// 密码
    /// </summary>
    [Required(ErrorMessage = "密码是必填的")]
    public string Password { get; set; }

    /// <summary>
    /// 确认密码
    /// </summary>
    [Required(ErrorMessage = "确认密码是必填的")]
    public string ConfirmPassword { get; set; }


}

public class RegisterCommandHandler : IRequestHandler<RegisterCommand, Result<bool>>
{
    private readonly ApplicationDbContext _context;
    private readonly IMapper _mapper;

    public RegisterCommandHandler(
        ApplicationDbContext context,
        IMapper mapper, ITokenService
        tokenService, IOptions<JwtSettings> optJwtSettings)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<Result<bool>> Handle(RegisterCommand request, CancellationToken cancellationToken)
    {
        ExceptionHelper.ThrowIfFalse(request.Password == request.ConfirmPassword, "两次密码不一致");

        var existingUser = await _context.Customers.FirstOrDefaultAsync(x => x.Username == request.Username || x.Email == request.Email, cancellationToken);
        if (existingUser != null)
        {
            ExceptionHelper.ThrowIfTrue(existingUser.Username == request.Username, $"用户名：{request.Username}已存在");
            ExceptionHelper.ThrowIfTrue(existingUser.Email == request.Email, $"邮箱：{request.Email}已存在");
        }

        var model = _mapper.Map<Customer>(request);
        model.HashPassword(request.Password);
        await _context.Customers.AddAsync(model);
        var result = (await _context.SaveChangesAsync()) > 0;

        return await Result<bool>.SucceedAsync(result, result, ["注册失败"]);
    }
}
